<template>
  <div class="slave-main">
    <el-dialog
      :title="caseStep.title"
      :visible.sync="caseStep.visible"
      width="80%"
      top="30px"
      @close="closeDialog(0)"
    >

      <div class="slave-main dialog-main">
        <div class="filter-container">
          <el-button
            class="filter-item"
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="addCaseStep()"
          >新增测试步骤</el-button>

        </div>
        <el-table
          border
          max-height="300"
          highlight-current-row
          :data="pageData"
          style="width: 100%"
          @selection-change="selectRowHandle"
        >
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column prop="id" label="ID" align="center" width="60" />
          <el-table-column prop="step_name" align="center" label="步骤名称" min-width="200" />
          <el-table-column prop="seq_num" align="center" label="序号" min-width="60" />
          <el-table-column prop="type" align="center" min-width="80" label="类型" />
          <el-table-column prop="step_count" align="center" label="逻辑控制" />
          <el-table-column prop="keyword" align="center" label="关键字" />
          <el-table-column prop="element_name" align="center" label="元素/用例片段" min-width="160" />
          <el-table-column prop="default_data" align="center" label="测试数据" :show-overflow-tooltip="true" min-width="160">
            <template slot-scope="{ row }">
              <template v-if="row.default_data === '{}'">
                <el-button type="text" size="small" circle @click="handleSettingData(row, 'default_data')">
                  配置
                </el-button>
              </template>
              <span v-else class="setting-data" @click="handleSettingData(row, 'default_data')">{{ parseJsonToParams(row.default_data) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="export_data" align="center" label="输出数据" :show-overflow-tooltip="true" min-width="160">
            <template slot-scope="{ row }">
              <template v-if="row.export_data === '{}'">
                <el-button type="text" size="small" circle @click="handleSettingData(row, 'export_data')">
                  配置
                </el-button>
              </template>
              <span v-else class="setting-data" @click="handleSettingData(row, 'export_data')">{{ parseJsonToParams(row.export_data) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="expected_result" align="center" label="预期结果" :show-overflow-tooltip="true" min-width="160">
            <template slot-scope="{ row }">
              <template v-if="row.expected_result === '{}'">
                <el-button type="text" size="small" circle @click="handleSettingData(row, 'expected_result')">
                  配置
                </el-button>
              </template>
              <span v-else class="setting-data" @click="handleSettingData(row, 'expected_result')">{{ parseJsonToParams(row.expected_result) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" align="center" label="创建时间" min-width="160" />
          <el-table-column prop="creator_name" align="center" label="创建人" min-width="130" />
          <el-table-column prop="mark" align="center" min-width="180" label="备注" />
          <el-table-column label="操作" fixed="right" header-align="center" align="center" min-width="130">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="editHandle(row,0)">复制</el-button>
              <el-button type="text" size="small" @click="editHandle(row,1)">编辑</el-button>
              <el-button type="text" size="small" @click="editHandle(row,2)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            :current-page="pageIndex"
            :page-sizes="[10, 15, 30, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addCase2Set, delCase2Set } from '@/api/caseSet'
import { listSteps, stepParams } from '@/api/caseStep'
import { parseJsonToParams, parseJsonToArray, CompareJsonObj } from '@/utils/jsonUtil.js'

export default {
  name: 'CaseSetManager',
  components: {
  },
  props: {
    caseStepItem: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      tableData: [],
      selectIds: [],
      filterTableData: [],
      pageSize: 10, // 每页大小默认值
      pageIndex: 1, // 默认第一页
      showDialog: false,
      caseStep: {
        casetId: '',
        title: '',
        visible: false
      },
      dataType: '',
      settingDataDialogVisible: false,
      stepDataParams: {},
      currentStep: {},
      stepData: {}
    }
  },
  computed: {
    // 总数
    total() {
      return this.filterTableData.length
    },
    // 当前分页数据
    pageData() {
      return this.filterTableData.slice((this.pageIndex - 1) * this.pageSize, this.pageIndex * this.pageSize)
    }

  },
  watch: {
    tableData() {
      this.pageIndex = 1
    }
  },
  mounted() {
    console.log(this.caseStepItem)
    this.caseStep = {
      caseId: this.caseStepItem.casetId,
      title: this.caseStepItem.title + '-测试步骤',
      visible: true
    }
    this.listStep()
  },
  methods: {
    closeDialog(flag) {
      this.showDialog = false
      this.$emit('closeDialog', flag)
    },
    selectRowHandle(selection) {
      this.selectIds = []
      const self = this
      selection.forEach(function(row) {
        self.selectIds.push(row.id)
      })
    },
    handleFilter() {
      const data = []
      Object.assign(data, this.tableData)
      this.filterTableData = data
    },
    // 前端分页： 当前页码改变
    handleCurrentChange(val) {
      this.pageIndex = val
    },
    // 前端分页：分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
    },
    // 获取用例列表
    listStep() {
      const params = {
        case_id: this.caseStepItem.caseId
      }
      listSteps(params).then(response => {
        this.tableData = response.data
        this.handleFilter()
      })
    },
    editHandle(row, state) {
      if (row.id === '' || row.id === undefined) {
        this.$message.error('未获取到测试用例id')
        return
      }

      if (state === 0) {
        const data = [row.id]
        this.$confirm('确定添加【' + row.case_title + '】测试集中吗 ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          addCase2Set(data, this.caseItem.set_id).then(response => {
            this.listCaseNotInManager()
            this.$message.success('添加成功')
          })
        }).catch(() => {
        })
      } else { // 删除
        const data = [row.map_id]
        this.$confirm('确定将【' + row.case_title + '】从测试集中删除吗 ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delCase2Set(data).then(response => {
            this.listCaseInManager()
            this.$message.success('删除成功')
          })
        }).catch(() => {
        })
      }
    },
    // 新增测试步骤
    addCaseStep() {

    },
    // 转换数据json=>key=value
    parseJsonToParams(data) {
      return parseJsonToParams(data)
    },
    // 配置不同类型的数据
    async handleSettingData(row, dataType) {
      this.listLoading = true
      this.dataType = dataType
      this.stepDataParams = {
        export_data: ['[自定义数据]']
      }
      this.stepData = {
        default_data: parseJsonToArray({
          data: row.default_data,
          insertEmpty: true,
          customData: {
            custom: true
          }
        }),
        export_data: parseJsonToArray({
          data: row.export_data,
          insertEmpty: true,
          customData: {
            custom: true
          }
        }),
        expected_result: parseJsonToArray({
          data: row.expected_result,
          insertEmpty: true,
          customData: {
            custom: true
          }
        })
      }
      this.currentStep = row
      // 从后台获取参数
      await stepParams({
        element_id: row.element_id,
        step_type: row.type,
        keyword_id: row.keyword_id,
        param_type: 'test_data'
      }).then(response => {
        this.stepDataParams.default_data = ['[自定义数据]'].concat(response.data)
      })

      await stepParams({
        element_id: row.element_id,
        step_type: row.type,
        keyword_id: row.keyword_id,
        param_type: 'expect'
      }).then(response => {
        this.stepDataParams.expected_result = ['[自定义数据]'].concat(response.data)
      })
      this.listLoading = false
      this.settingDataDialogVisible = true
    },
    // 关闭数据编辑窗口 处理数据
    closeDataSetting(data) {
      this.settingDataDialogVisible = false
      if (typeof data === 'object') {
        for (const k in data) {
          if (!CompareJsonObj(JSON.parse(this.currentStep[k]), data[k])) {
            this.currentStep[k] = JSON.stringify(data[k])
            this.currentStep.updated = true
          }
        }
      }
    }

  }
}
</script>

<style scoped>
  .el-dialog__body {
    padding: 10px 20px;
  }

  .dialog-main {
    height: 410px;
    /* overflow-y: auto; */
  }
</style>
